import React, { useState, useEffect, useRef } from 'react';
import { Upload, message, Spin, Typography } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { useSearchUIDispatch } from '../../../../../store/hooks/useSearchUIDispatch';
import { uploadSearchImg } from '../../../service'
import './index.less';
import PutImg from '../../../Icon/PutImg';

const SearchImgPanel = (props: any) => {
  const [isType, $isType] = useState(true)
  const [loading, $loading] = useState(false)
  const uploadRef = useRef()
  const [uploadWidth, $uploadWidth] = useState(375)
  const { $visible, onOk, customClassName, divRef, visible } = props;
  const updateUIState = useSearchUIDispatch();
  const closeUploadBox = () => {
    $visible(false)
    updateUIState({
      showSearchResultPanel: false,
    })
  }

  const UploadProps = {
    name: 'file',
    showUploadList: false,
    headers: {

    },

    action: `/ImageSearch/Upload`,
    beforeUpload(info: any) {
      const isPNG = ['jpg', 'jpeg', 'png', 'bmg', 'gif']
      const imgtype = info.name.substring(info.name.lastIndexOf('.') + 1)
      const index = isPNG.indexOf(imgtype)
      if (index == -1) {
        $isType(false)
        return false
      } else {
        if (info.size > 0) {
          if (info.size > 10485760) {
            message.error(`${getMessage('SearchEngine.uploadError')}`)
            return false
          }
        } else {
          message.error(`${info.name} ${getMessage('SearchEngine.uploadSize')}M`)
          return false
        }
      }
      return info
    },
    onChange(info: any) {
      $loading(true)
      if (info.file.status !== 'uploading') {
        $loading(false)
      }

      if (info.file.response) {
        if (info.file.response.nResult == 0) {
          message.success(`${info.file.name} ${getMessage('SearchEngine.uploadSuccess')}`);
          $visible(false)
          onOk(info.file.response)

        } else {
          message.info(info.file.response.msg);
        }

        $loading(false)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} ${getMessage('SearchEngine.uploadFail')}`);
        $visible(true)
        $loading(false)
      }
    },
  };

  const pasteSearch = (e) => {
    const copyData = e.clipboardData
    const { items } = copyData;

    let blob = null;
    if (items[0].type.startsWith('image')) {
      blob = items[0].getAsFile()
    }
    if (blob) {
      $loading(true)
      uploadSearchImg(blob).then(res => {
        if (res.nResult == 0) {
          onOk(res)
        }
        $loading(false)
      })
    }
  }

  useEffect(() => {
    if (visible) {
      divRef.current?.addEventListener('paste', pasteSearch);
      const uploadPanel: any = uploadRef.current;
      $uploadWidth(uploadPanel.clientWidth - 60)
      return () => {
        divRef.current?.removeEventListener('paste', pasteSearch);
      }
    }

  }, [])
  return (
    <Spin spinning={loading}>
      <div className={customClassName ? customClassName : 'searchImgPanel'}>
        <div className="uploadBoxClose">
          <InbizIcon
            style={{ fontSize: 20, color: '#999', marginRight: 15 }}
            className='uploadBoxCloseIcon'
            type="icon-guanbi-yeqian"
            onClick={closeUploadBox}
          />
        </div>
        <div className="uploadGroup" ref={uploadRef}>
          <Upload {...UploadProps}>
            <div className="uploadGroupImg">
              <div className='imgInfo'>
                {isType ? (
                  <div className='uploadIcon'>
                    <PutImg />
                  </div>
                ) : (<></>)}
                <div className='uploadTextDisplay'>
                  <span className='uploadText'>
                    {isType ? <TextWidget>SearchEngine.uploadInfo</TextWidget> : <TextWidget>SearchEngine.uploadInfoError</TextWidget>}
                  </span>
                  <span className='uploadImg'>
                    {isType ? <TextWidget>SearchEngine.uploadImg</TextWidget> : <TextWidget>SearchEngine.uploadImgError</TextWidget>}
                  </span>
                </div>

              </div>
            </div>
          </Upload>
          <div className="uploadHeader">
            <span className="uploadHeaderText">
              <Typography.Text ellipsis style={{ width: uploadWidth }} title={getMessage('SearchEngine.uploadRequirements')}>
                <TextWidget>SearchEngine.uploadRequirements</TextWidget>
              </Typography.Text>
            </span>
          </div>
        </div>
      </div>
    </Spin>
  )
}

export default SearchImgPanel;
